<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax+template 获取新闻列表</title>
    <!-- jQuery -->
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <!-- 1 导入模板引擎 -->
    <!-- 提供一个全局函数  template('模板的id',需要渲染的数据) -->
    <script src="./js/template-web.js"></script>
    <link rel="stylesheet" href="./asserts/news.css">

</head>
<body>

    <div id="news-list">

    </div>

    <!-- 2 、定义模板 -->
    <script type="text/html" id="tpl-news">
        {{each arr}}
        <div class="news-item">
            <img class="thumb" src="{{'http://www.liulongbin.top:3006' + $value.img}}" alt="">
            <div class="right-box">
                <h1 class="title">{{$value.title}}</h1>
                <div class="tags">
                    {{each $value.tags}}
                    <span>{{$value}}</span>
                    {{/each}}
                </div>
            
                <div class="footer">
                    <div>
                        <span>{{$value.source}}</span>&nbsp;&nbsp;
                        <span>{{$value.time | dateFormat}}</span>
                    </div>
                    <span>评论数：{{$value.cmtcount}}</span>
                </div>
            </div>
        </div>
        {{/each}}
    </script>

    <script>
        // 定义时间格式化
        template.defaults.imports.dateFormat = function(date){
            // console.log(date)
            var d = new Date(date);
            // console.log(d)
            var y = d.getFullYear();
            var m = d.getMonth();
            var dd = d.getDate();

            var hh = d.getHours();
            var mm = d.getMinutes();
            var ss = d.getSeconds();
            return y + '-' + m + '-' + dd + ' ' + hh + ':' + mm + ':' + ss;
        }

        // 获取新闻列表
        function getNewsList(){
            $.get('http://www.liulongbin.top:3006/api/news', function(result){
                // console.log(result)
                let {data, status} = result;
                if(status != 200){
                    return alert("获取新闻列表失败")
                }
                for(var i = 0; i < data.length; i++){
                    // 将每一项的字符串改成数组
                    data[i].tags = data[i].tags.split(',');
                }
                // 1、渲染的数据
                // console.log(data);

                // 3、 调用template函数 {data: xxx}
                var htmlStr = template('tpl-news', {arr:data});
                $("#news-list").html(htmlStr);
            })
        }

        getNewsList()

    </script>
</body>
</html>